//
//  serverManger.swift
//  TCPService
//
//  Created by adel on 2017/9/20.
//  Copyright © 2017年 adel. All rights reserved.
//

import Cocoa
import SwiftSocket
class serverManger: NSObject {
    
    fileprivate lazy var serverSocket = TCPServer(address: "0.0.0.0", port: 12345)
    fileprivate var isStartRuning: Bool = false
    fileprivate var clients : [ClientManger] = [ClientManger]()
}


extension serverManger{
    
    func startServer() -> Bool{
    
    //1.监听
    if serverSocket.listen().isSuccess {
       
        print("服务端已开启")
        
        //2.接收客户端
        DispatchQueue.global().async {
            
            while true {
            if let client = self.serverSocket.accept() {
                self.handleClient(client)
            }
            }
        }
        
        return true
    }else{
        
        print(serverSocket.listen().error!)
    }
    
        return false
    }
    
    
    func closeServer() {
        
        serverSocket.close()
        
    }
}


extension serverManger{
    
    fileprivate func handleClient(_ client : TCPClient){
        
        print("与客户端连接建立成功")
        let client = ClientManger(tcpClient: client)
        client.startReadMsg()
        clients.append(client)
        
    }
}
